//
//  KAEdgeLabel.swift
//  kano
//
//  Created by Frank on 2024/12/20.
//

import UIKit

class KAEdgeLabel: UILabel {
    
    // 用于设置edgeInsets
    var edgeInsets: UIEdgeInsets = .zero
    
    // 初始化方法，传入edgeInsets
    init(edgeInsets: UIEdgeInsets) {
        super.init(frame: .zero)
        self.edgeInsets = edgeInsets
    }
    
    // 初始化方法，传入frame，默认有UIEdgeInsets
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.edgeInsets = UIEdgeInsets(top: 0, left: 2, bottom: 0, right: 2)
    }
    
    // 用编码初始化
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.edgeInsets = UIEdgeInsets(top: 0, left: 2, bottom: 0, right: 2)
    }
    
    // 如果是从XIB文件加载，调用此方法
    override func awakeFromNib() {
        super.awakeFromNib()
        self.edgeInsets = UIEdgeInsets(top: 0, left: 2, bottom: 0, right: 2)
    }
    
    
    // 重写 hitTest 方法来处理点击区域
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        let insetsRect = bounds.inset(by: edgeInsets) // 调整后的点击区域
        return insetsRect.contains(point) ? self : nil
    }
    
    // 重写textRectForBounds方法以增加edgeInsets
    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        // 调用父类的方法，注意传入的是应用了edgeInsets的bounds
        let rect = super.textRect(forBounds: bounds.inset(by: self.edgeInsets), limitedToNumberOfLines: numberOfLines)
        
        // 根据edgeInsets调整绘制文字的bounds
        var adjustedRect = rect
        adjustedRect.origin.x -= self.edgeInsets.left
        adjustedRect.origin.y -= self.edgeInsets.top
        adjustedRect.size.width += self.edgeInsets.left + self.edgeInsets.right
        adjustedRect.size.height += self.edgeInsets.top + self.edgeInsets.bottom
        
        return adjustedRect
    }
    
    // 重写drawTextInRect方法，增加内边距
    override func drawText(in rect: CGRect) {
        // 将绘制区域应用内边距
        super.drawText(in: rect.inset(by: self.edgeInsets))
    }
}
